/**
 入驻小区
 **/
(function (vc) {
    var DEFAULT_PAGE = 1;
    var DEFAULT_ROWS = 2;
    vc.extends({
        data: {
            cameraControlVideoInfo: {
                paId: '',
                inMachineId: '',
                outMachineId: '',
                machines: [],
                showType: '606',
                outMachines: [],
                websocketUrl: '',
                clientId: '',
                rows: '2',
                boxId: '',
                sipDatas: [],
                _beforeUnload_time: ''

            }
        },
        _initMethod: function () {
            $that.cameraControlVideoInfo.clientId = vc.uuid();
            $that._listMachines(DEFAULT_PAGE, DEFAULT_ROWS);
        },
        _initEvent: function () {
            vc.on('cameraControlVideo', 'notify', function (param) {
            })
            vc.on('pagination', 'page_event', function (_currentPage) {
                vc.component._listMachines(_currentPage, DEFAULT_ROWS);
            });
            vc.on('cameraControlInfo', 'page_event', function () {
                vc.component._listMachines(DEFAULT_PAGE, $that.cameraControlVideoInfo.rows);
            });
        },
        methods: {
            _listMachines: function (_page, _rows) {
                let param = {
                    params: {
                        page: _page,
                        row: _rows,
                        isShow: 'Y',
                        caId: vc.getCurrentCommunity().caId
                    }
                }
                //发送get请求
                vc.http.apiGet('/machineStaffShow/queryMachineStaffShow',
                    param,
                    function (json, res) {
                        let _machineManageInfo = JSON.parse(json);
                        $that.cameraControlVideoInfo.machines = _machineManageInfo.data;
                        if ($that.cameraControlVideoInfo.machines.length < 1) {
                            return;
                        }
                        let _machine = $that.cameraControlVideoInfo.machines[0];
                        $that.cameraControlVideoInfo.websocketUrl = _machine.websocketUrl;
                        $that.cameraControlVideoInfo.machines.forEach(element => {
                            $that._initMachineVideo(element.machineId, $that.cameraControlVideoInfo.clientId);
                        });
                        //启动webscoket
                        $that._initParkingAreaWs();

                        vc.emit('pagination', 'init', {
                            total: _machineManageInfo.records,
                            currentPage: _page
                        });
                        vc.emit('cameraControlInfo', 'notify', {
                            _machine
                        });
                    }, function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
            _initMachineVideo: function (_machineId, _clientId) {
                if (!_machineId) {
                    return;
                }
                console.log(_machineId);
                let param = {
                    params: {
                        page: 1,
                        row: 10,
                        caId: vc.getCurrentCommunity().caId,
                        machineId: _machineId,
                        clientId: _clientId
                    }
                }
                //发送get请求
                vc.http.apiGet('/machine/checkMachine',
                    param,
                    function (json, res) {
                        let _machineManageInfo = JSON.parse(json);
                        $that.cameraControlVideoInfo.sipDatas = _machineManageInfo;
                        if ($that.cameraControlVideoInfo.sipDatas.code == "1") {
                            vc.message($that.cameraControlVideoInfo.sipDatas.msg);
                        }
                        console.log($that.cameraControlVideoInfo.sipDatas.msg);
                        $that._playVideo($that.cameraControlVideoInfo.sipDatas.machineId, $that.cameraControlVideoInfo.sipDatas.url);
                    }, function (errInfo, error) {
                        console.log('请求失败处理');
                    }
                );
            },
            _onCameraControlInfo: function (_machine) {
                vc.emit('cameraControlInfo', 'notify', {
                    _machine
                });
            },
            _selectVideo: function (_machine) {
                $that._listMachines(DEFAULT_PAGE, $that.cameraControlVideoInfo.rows);
            },
            _deletedMachine: function (_machine) {
                let params = {
                    machineStaffId: _machine.machineStaffId,
                    caId: _machine.caId,
                    isShow: 'N'
                }
                vc.http.apiPost(
                    '/machineStaffShow/deleteMachineStaffShow',
                    JSON.stringify(params),
                    {
                        emulateJSON: true
                    },
                    function (json, res) {
                        //vm.menus = vm.refreshMenuActive(JSON.parse(json),0);
                        let _json = JSON.parse(json);
                        if (_json.code == 0) {
                            //关闭model
                            vc.message(_json.msg);
                            vc.component._listMachines(DEFAULT_PAGE, DEFAULT_ROWS);
                            return;
                        }
                        vc.message(_json.msg);

                    },
                    function (errInfo, error) {
                        console.log('请求失败处理');

                        vc.message(errInfo);

                    });
            },
            _playVideo: function (_videoId, url) {
                $('#' + _videoId).show();
                let sdk = null; // Global handler to do cleanup when replaying.
                sdk = new SrsRtcPlayerAsync();
                $('#' + _videoId).prop('srcObject', sdk.stream);
                sdk.play(url).then(function (session) {
                }).catch(function (reason) {
                    sdk.close();
                    $('#' + _videoId).hide();
                    console.error(reason);
                });
            },
            _initParkingAreaWs: function () {
                let clientId = $that.cameraControlVideoInfo.clientId;
                let heartCheck = {
                    timeout: 30000,        // 9分钟发一次心跳，比server端设置的连接时间稍微小一点，在接近断开的情况下以通信的方式去重置连接时间。
                    serverTimeoutObj: null,
                    pingTime: new Date().getTime(),
                    reset: function () {
                        clearTimeout(this.serverTimeoutObj);
                        return this;
                    },
                    start: function () {
                        let self = this;
                        this.serverTimeoutObj = setInterval(function () {
                            if (websocket.readyState == 1) {
                                console.log("连接状态，发送消息保持连接");
                                let _pingTime = new Date().getTime();
                                //保护，以防 异常
                                if (_pingTime - self.pingTime < 15 * 1000) {
                                    return;
                                }
                                websocket.send("{'cmd':'ping'}");
                                self.pingTime = _pingTime;

                                heartCheck.reset().start();    // 如果获取到消息，说明连接是正常的，重置心跳检测
                            } else {
                                console.log("断开状态，尝试重连");
                                $that._initParkingAreaWs();
                            }
                        }, this.timeout)
                    }
                }

                let _protocol = window.location.protocol;
                let url = '';
                if (_protocol.startsWith('https')) {
                    url =
                        "wss://" + $that.cameraControlVideoInfo.websocketUrl + "/ws/parkingArea/" + clientId;
                } else {
                    url =
                        "ws://" + $that.cameraControlVideoInfo.websocketUrl + "/ws/parkingArea/" + clientId;
                    // url =
                    //     "ws://demo.homecommunity.cn:9011/ws/parkingArea/" +
                    //     $that.parkingAreaControlInfo.boxId + "/" + clientId;
                }


                if ("WebSocket" in window) {
                    websocket = new WebSocket(url);
                } else if ("MozWebSocket" in window) {
                    websocket = new MozWebSocket(url);
                } else {
                    websocket = new SockJS(url);
                }

                //连接发生错误的回调方法
                websocket.onerror = function (_err) {
                    console.log("初始化失败", _err);
                    this.$notify.error({
                        title: "错误",
                        message: "连接失败，请检查网络"
                    });
                };

                //连接成功建立的回调方法
                websocket.onopen = function () {
                    heartCheck.reset().start();
                    websocket.send(JSON.stringify($that.cameraControlVideoInfo.machines));
                    console.log("ws初始化成功");
                };
                //连接关闭的回调方法
                websocket.onclose = function () {
                    console.log("初始化失败");
                    //$that._initParkingAreaWs();
                    this.$notify.error({
                        title: "错误",
                        message: "连接关闭，请刷新浏览器"
                    });
                };
                //接收到消息的回调方法
                websocket.onmessage = function (event) {
                    heartCheck.reset().start();
                    console.log("event", event);
                    let _data = event.data;
                    try {
                        _data = JSON.parse(_data);
                    } catch (err) {
                        return;
                    }
                };
                //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
                window.onbeforeunload = function () {
                    websocket.close();
                };
            }
        }

    });
})(window.vc);